package controllers;

import models.Movie;
import models.Project;
import models.view.Ret;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import play.mvc.Controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Application extends Controller {

    private static String WEB = "http://www.btbtt.co/";

    public static void index() {
        List<Movie> movies = Movie.findAll();
        List<String> groups = new ArrayList<>();
        for(Movie movie : movies) {
            if(!groups.contains(movie.groupName))
                groups.add(movie.groupName);
        }
        render(movies, groups);
    }

    public static void makePlan(String name, String href, String groupName) {
        Project project = new Project();
        project.name = name;
        project.href = href;
        project.groupName = groupName;
        if(Project.count("href=?", href) > 0) {
            renderJSON(new Ret(false, "已经定制过了"));
        }
        try {
            Document document = Jsoup.connect(href).get();
            Elements p = document.select("table.post_table").select("div").select("p");
            String img = p.get(0).select("img").attr("src");
            project.img = WEB + img;
            project.type = Movie.T.MEDIUM;
        } catch(IOException e) {
            e.printStackTrace();
        }
        project.createDate = new Date();
        project.save();
        renderJSON(new Ret(true));
    }

    public static void makePlanIndex() {
        List<Project> projects = Project.findAll();
        render(projects);
    }

    public static void indexSearch(String search) {
        List<Project> projects = new ArrayList<>();
        if(StringUtil.isBlank(search))
            render(projects);
        try {
            String path = WEB + "search-index-keyword-" + search + ".htm";
            Document document = Jsoup.connect(path).get();
            Element body = document.getElementById("threadlist");
            Elements divs = body.select("table");

            for(Element table : divs) {
                Project project = new Project();
                project.name = table.select("a.subject_link").text();
                project.href = WEB + table.select("a.subject_link").attr("href");
                projects.add(project);
            }
            render(search, projects);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void projectIndex(String url) {
        List<Movie> movies = new ArrayList<>();

        render(movies);
    }
}